#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Desc  : 性能测试脚本
"""
import os
import sys
import time

import pandas as pd


def start_statistics(filepath):
    for thread in thread_list:
        dest_file = open(thread + '.txt', 'a')
        with open(filepath, 'rb') as file:
            while True:
                # 按行读取
                line = file.readline().decode('utf-8', errors='ignore')
                if line:
                    if thread in line:
                        dest_file.write(line)
                else:
                    break
        dest_file.close()

def cat_all_file():
    path = sys.argv[0][0:sys.argv[0].rfind("/")]  # 文件夹目录
    files = os.listdir(path)  # 得到文件夹下的所有文件名称
    for file in files:  # 遍历文件
        f = open(path + "\\" + file).read()  # 将打开的文件内容保存到变量f
        log = open(path + "\\" + '合成.log', 'a+')  # 以追加模式打开文件
        log.write(f)  # 写入文件
        print('已经合并：' + file)

def get_thread_top(thread_path, seconds):
    """
    :param thread_path:线程性能文件路径
    :param seconds:需要执行抓取性能的时间
    """
    global write_wav_cpu_info

    f2 = open(thread_path, "r")

    thread_name_list = {}
    line = f2.readline()
    process_name_dict = {}
    while len(line) > 0:
        try:
            line = line.replace("\n", "")
            ret = line.split()

            if len(ret) < 10:
                line = f2.readline()
                continue

            cpu = ret[8]
            if isfloat(cpu) or cpu.isdigit():
                cpu_info = float(cpu)
            else:
                line = f2.readline()
                continue

            if cpu_info < 0 or cpu_info > 300:
                line = f2.readline()
                continue
            thread_id = ret[0]
            process_name_dict[thread_id] = ret[-1]
            pid_name = ret.pop()
            thread_name = ret.pop()

            if pid_name not in thread_name_list:
                thread_name_list[pid_name] = {}

            if thread_id in thread_name_list[pid_name]:
                thread_name_list[pid_name][thread_id].append(cpu_info)
            else:
                thread_name_list[pid_name][thread_id] = []
                thread_name_list[pid_name][thread_id].append(thread_name)
                thread_name_list[pid_name][thread_id].append(cpu_info)

        except Exception as e:
            print(e.args)
        line = f2.readline()

    thread_result_list = []
    for process in thread_name_list:
        for thread in thread_name_list[process]:
            thread_name = thread_name_list[process][thread].pop(0)
            sum_thread = round(sum(thread_name_list[process][thread]), 3)
            max_thread = round(max(thread_name_list[process][thread]), 3)
            len_thread = len(thread_name_list[process][thread])
            avg_thread = round(sum_thread / len_thread, 3)
            thread_result_list.append(
                [thread, thread_name, process_name_dict.get(thread), sum_thread, len_thread, avg_thread, max_thread,
                 round(sum_thread / seconds, 3)])
            if process == "android.hardware.audio.service" and thread == "write_wav":
                write_wav_cpu_info = round(sum_thread / seconds, 3)

    df_thread_result = pd.DataFrame(thread_result_list)

    df_thread_result.columns = ["线程ID", "线程名", "进程名", "CPU总和", "抓取次数总和",
                                "采样次数CPU均值(CPU总和/抓取次数总和)", "峰值", "采样时长CPU均值"]
    df_sort = df_thread_result.sort_values(by=['进程名', 'CPU总和'], ascending=False)
    df_sort.to_csv(RESULT_LOG + "/result_thread.csv", index=False, encoding="utf_8_sig")
    f2.close()
    return

def isfloat(string):
    """
    判断字符串可以转浮点数
    :param string:需要判断的字符串
    """
    s = string.split('.')
    if len(s) != 2:
        return False
    else:
        for si in s:
            if not si.isdigit():
                return False
        return True

def getDateTimeStr():
    """获取日期时间
    @:return eg.20190101120030
    """
    return time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))

if __name__ == "__main__":
    global RESULT_LOG
    CONFIG_DIR = os.path.dirname(os.path.abspath(__file__))
    RESULT_LOG = os.path.join(CONFIG_DIR, ("%s_" + "wp_asr") % getDateTimeStr())
    if not os.path.exists(RESULT_LOG):
        os.makedirs(RESULT_LOG)

    package_list = ["com.baidu.che.codriver"]
    thread_list = ["spil_process", "wak_vad", "bd_doa", "sdk_rd", "sdk_rd_ms_read", "pcm_write_write", "sdk_buf_read",
                   "bd_wpe", "sdk_ctx_run", "sdk_rd_ms_write"]
    # start_statistics(sys.argv[1])
    get_thread_top("/Users/v_lipengcheng/Desktop/before_cpu_thread.txt", 600)
